package com.wcpdoc.exam.api.controller;

import com.alibaba.excel.EasyExcel;
import com.wcpdoc.core.controller.BaseController;
import com.wcpdoc.core.entity.PageIn;
import com.wcpdoc.core.entity.PageOut;
import com.wcpdoc.core.entity.PageResult;
import com.wcpdoc.core.entity.PageResultEx;
import com.wcpdoc.core.exception.MyException;
import com.wcpdoc.exam.api.controller.excel.MockUserEntity;
import com.wcpdoc.exam.api.controller.excel.UserEntity;
import com.wcpdoc.exam.report.service.MockReportService;
import com.wcpdoc.exam.report.service.ReportService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 成绩报表控制层
 * <p>
 * v1.0 zhanghc 2017年8月29日下午2:03:36
 *
 * @date
 */
@Controller
@RequestMapping("/api/mockReport")
public class ApiMockReportController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(ApiMockReportController.class);

    @Resource
    private MockReportService mockReportService;


    /**
     * 试题统计
     * <p>
     * v1.0 chenyun 2021-12-15 13:44:47
     *
     * @return PageResult
     */
    @RequestMapping("/question/statis")
    @ResponseBody
    public PageResult questionStatis(Integer questionTypeId) {
        try {
            return PageResultEx.ok().data(mockReportService.mockQuestionStatis(questionTypeId));
        } catch (MyException e) {
            log.error("试题统计错误：{}", e.getMessage());
            return PageResult.err().msg(e.getMessage());
        } catch (Exception e) {
            log.error("试题统计错误：", e);
            return PageResult.err();
        }
    }


    /**
     * 考试统计
     * <p>
     * v1.0 chenyun 2021-12-15 13:44:47
     *
     * @param examId
     * @return PageResult
     */
    @RequestMapping("/mockExam/statis")
    @ResponseBody
    public PageResult mockExamStatis(Integer examId) {
        try {
            return PageResultEx.ok().data(mockReportService.mockExamStatis(examId));
        } catch (MyException e) {
            log.error("考试统计错误：{}", e.getMessage());
            return PageResult.err().msg(e.getMessage());
        } catch (Exception e) {
            log.error("考试统计错误：", e);
            return PageResult.err();
        }
    }

    /**
     * 模考导出
     *
     * @param response
     * @param examId
     * @return void
     * @author 王晶
     * @date 2024/4/20 23:04
     */
    @RequestMapping("/mockExam/export")
    public void mockExamExportExcel(HttpServletResponse response, Integer examId) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        List<Map<String, Object>> data = mockReportService.mockExportFile(examId);


        log.info("导出的数据是:{}", data);


        List<MockUserEntity> dataList = new ArrayList<>();
        for (Map<String, Object> map : data) {
            MockUserEntity dataItem = new MockUserEntity();

            dataItem.setLoginName(String.valueOf(map.get("loginName")));
            dataItem.setSex(String.valueOf(map.get("sex")));
            dataItem.setLabelName(String.valueOf(map.get("labelName")));

            dataItem.setMyExamNo(String.valueOf(map.get("myMockExamNo")));

            dataItem.setUserName(String.valueOf(map.get("userName")));
            dataItem.setOrgName(String.valueOf(map.get("orgName")));
            dataItem.setMyExamTotalScore(String.valueOf(map.get("myMockExamTotalScore")));
            dataItem.setMyExamState(String.valueOf(map.get("myMockExamState")));

            dataItem.setMyMockExamStartTime(String.valueOf(map.get("myMockExamStartTime")));
            dataItem.setMyMockExamEndTime(String.valueOf(map.get("myMockExamEndTime")));


            dataList.add(dataItem);
        }

        // 文件名
        String fileName;
        fileName = "模考排名";
        try {
            // 文件名，编码格式
            fileName = URLEncoder.encode(fileName, "UTF-8");

            // 文件格式
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            // 使用EasyExcel工具写excel
            EasyExcel.write(response.getOutputStream(), MockUserEntity.class).sheet("logs").doWrite(dataList);

        } catch (IOException e) {
            e.printStackTrace();
            throw new MyException("导出错误！");
        }
    }


    /**
     * @return PageResult
     * @desc 考试排名列表
     * @author 王晶
     * @date 2024/4/20 23:23
     */
    @RequestMapping("/mockExam/rankListpage")
    @ResponseBody
    public PageResult mockExamRankListpage() {
        try {// 不校验，任何时候都能查询
            PageOut pageOut = mockReportService.mockExamRankListpage(new PageIn(request));
            for (Map<String, Object> map : pageOut.getList()) {
                Integer examMarkType = (Integer) map.get("examMarkType");
                Integer examMarkState = (Integer) map.get("examMarkState");
                if (examMarkType == 2 && examMarkState != 3) {// 如果是主观题试卷，且考试未结束，不显示分数
                    map.put("myExamTotalScore", null);// 阅完一张会打分，但是会二次修改分数，不应该显示中间状态
                }
            }
            return PageResultEx.ok().data(pageOut);
        } catch (MyException e) {
            log.error("考试排名错误：{}", e.getMessage());
            return PageResult.err().msg(e.getMessage());
        } catch (Exception e) {
            log.error("考试排名错误：", e);
            return PageResult.err();
        }
    }


}
